﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;

namespace down2.api
{
    /// <summary>
    /// 读取指定路径文件夹返回JSON
    /// </summary>
    public partial class dir : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var file_url = Request.Url.AbsoluteUri;
            var pos = file_url.IndexOf("dir.aspx");
            file_url = file_url.Substring(0, pos);
            file_url = file_url + "file.aspx";
            var path = Request.QueryString["path"];
            var base64 = Request.QueryString["base64"];//对路径进行编码,1,0
            //路径为空
            if (string.IsNullOrEmpty(path))
            {
                Response.StatusCode = 500;
                Response.Write("路径为空");
                Response.End();
            }
            path = path.Trim();
            path = path.Replace("/", "\\");
            path = Server.UrlDecode(path);

            //目录不存在
            if (!Directory.Exists(path))
            {
                Response.StatusCode = 500;
                Response.Write("路径不存在");
                Response.End();
            }

            //目录表,路径,名称
            var dirDic = new Dictionary<string, JObject>();
            //添加根目录
            dirDic.Add(path, new JObject {
                { "nameLoc",Path.GetFileName(path)},
                { "pathSvr",path},
                {"files",new JArray{ } },
                {"folders",new JArray{ } }
            });

            //子目录列表
            var dirChilds = new Dictionary<string, List<JObject>>();

            //获取所有目录
            var dirs = Directory.GetDirectories(path,"*", SearchOption.AllDirectories);
            foreach (var dir in dirs) {
                var dn = Path.GetFileName(dir);

                //添加当前节点
                if (!dirDic.ContainsKey(dir))
                {
                    var obj = new JObject {
                        {"nameLoc",dn },
                        {"pathSvr",dir},
                        {"files",new JArray{ } },
                        {"folders",new JArray{ } } };
                    dirDic.Add(dir, obj);

                    //添加到父级
                    var prt = Path.GetDirectoryName(dir);
                    if(dirChilds.ContainsKey(prt))
                    {
                        dirChilds[prt].Add(obj);
                    }//不存在
                    else { 
                        dirChilds.Add(prt,new List<JObject>{obj});
                    }
                }
            }

            //取所有文件
            var files = Directory.GetFiles(path,"*.*",SearchOption.AllDirectories);
            //获取所有目录表
            foreach (var file in files) 
            { 
                //父路径
                var prt = Path.GetDirectoryName(file);
                var fn = Path.GetFileName(file);
                var fin = new FileInfo(file);
                var url = Base64Encoder.build().encode(file);
                if (string.IsNullOrEmpty(base64)) url = file;

                JObject dir = dirDic[prt];
                var fs = (JArray)dir["files"];
                fs.Add(new JObject {
                    { "fileUrl", file_url+"?path=" + url } ,
                    { "nameLoc",fn},
                    { "query",false },
                    { "lenSvr",fin.Length}
                });
            }

            //构建层级路径
            this.addChilds(dirDic[path], dirChilds);

            Response.AddHeader("Content-Type", "application/json");
            Response.Write(dirDic[path]);
        }

        void addChilds(JObject prt, Dictionary<string, List<JObject>> childs)
        {
            //目录列表
            var fds = (JArray)prt["folders"];
            var path = prt["pathSvr"].ToString();
            if (!childs.ContainsKey(path)) return;
            //遍历添加子目录
            foreach (JObject o in childs[path])
            {
                fds.Add(o);
                addChilds(o, childs);
            }
        }
    }
}